<?php

namespace app\service;

use app\model\Menu;
use app\traits\Singleton;

class MenuService
{
    use Singleton;

    public function getMenuList()
    {
        return Menu::with(["children"])
            ->where("pid", "=", 0)
            ->order("sort", "desc")
            ->select()
            ->toArray();
    }

    public function getMenusByPermission($permissionIds)
    {
        // 获取所有菜单
        $menus = Menu::with(["children"])
            ->where("pid", "=", 0)
            ->order("sort", "desc")
            ->select()
            ->toArray();

        // 递归过滤菜单
        $filterMenus = $this->filterMenuTree($menus, $permissionIds);
        return $filterMenus;
    }

    private function filterMenuTree($menus, $permissionIds)
    {
        $filtered = [];
        foreach ($menus as $menu) {
            // 检查当前菜单是否有权限，或者有子菜单有权限
            $hasPermission = in_array($menu['id'], $permissionIds);
            if (isset($menu['children']) && is_array($menu['children'])) {
                $menu['children'] = $this->filterMenuTree($menu['children'], $permissionIds);
                $hasChildPermission = count($menu['children']) > 0;
            } else {
                $hasChildPermission = false;
            }

            // 如果当前菜单有权限，或者有子菜单有权限，则保留
            if ($hasPermission || $hasChildPermission) {
                $filtered[] = $menu;
            }
        }
        return $filtered;
    }

    public function createMenu($name, $pid, $icon, $url)
    {
        return Menu::create([
            'name' => $name,
            'pid' => $pid,
            'icon' => $icon,
            'url' => $url,
        ]);
    }

    public function updateMenu($id, $name, $pid, $icon, $url)
    {
        return Menu::where("id", $id)->save([
            'name' => $name,
            'pid' => $pid,
            'icon' => $icon,
            'url' => $url,
        ]);
    }

    public function deleteMenu($id)
    {
        return Menu::where("id", $id)->delete();
    }
}